<?php
/**
 * Created by PhpStorm.
 * User: hoter.zhang
 * Date: 2017/8/21
 * Time: 14:07
 */

namespace app\controllers;


use app\core\lib\Controller;
use app\models\Post;
use app\models\PostCate;
use Yii;
use yii\data\ActiveDataProvider;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;

class PostController extends Controller
{

    public function behaviors()
    {
        return [
            [
                'class' => 'yii\filters\HttpCache',
//                'only' => ['index'],
                'etagSeed' => function($action, $params){
                    return serialize(date('Y-m-d'));
                }
            ]
        ];
    }

    public function actionIndex(){
        $defaultCateInfo = PostCate::find()->one();
        $defaultCid = ($defaultCateInfo !== null) ? $defaultCateInfo->id : 1;
        $cid = Yii::$app->request->get('cid', $defaultCid);

        $postCate = PostCate::find()->asArray()->all();
        $query = Post::find()->where(['cid'=>$cid]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
//                'defaultPageSize' => 1,
                'pageSize' => 8
            ]
        ]);

        return $this->render('index',[
            'postCate' => $postCate,
            'dataProvider' => $dataProvider,
            'defaultCid' => $defaultCid
        ]);
    }

    public function actionView($id){
        $model = $this->findModel($id);
        //上一篇
        $prev = Post::find()
            ->andFilterWhere(['<', 'id', $id])
            ->limit(1)
            ->one();
        //下一篇
        $next = Post::find()
            ->andFilterWhere(['>', 'id', $id])
            ->limit(1)
            ->one();
        $page['prev'] = [
            'title' => !is_null($prev) ? $prev->title : '没有了',
            'url' => !is_null($prev) ? Url::current(['id'=>$prev->id]) : 'javascript:;'
        ];
        $page['next'] = [
            'title' => !is_null($next) ? $next->title : '没有了',
            'url' => !is_null($next) ? Url::current(['id'=>$next->id]) : 'javascript:;'
        ];

        //最新文章
        $newPosts = Post::find()->limit(4)->orderBy(['created_at'=>SORT_DESC])->asArray()->all();

        return $this->render('view',[
            'model' => $model,
            'page' => $page,
            'newPosts' => $newPosts
        ]);
    }

    protected function findModel($id)
    {
        if (($model = Post::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}